package com.mengchengnet.chaperonage.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.mengchengnet.chaperonage.BaseActivity;
import com.mengchengnet.chaperonage.BaseFragment;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.ui.fragment.ChaperonageFragment;
import com.mengchengnet.chaperonage.ui.fragment.HomeFragment;
import com.mengchengnet.chaperonage.ui.fragment.MineFragment;
import com.mengchengnet.chaperonage.util.PermissionsChecker;
import com.mengchengnet.chaperonage.util.PreferenceUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends BaseActivity {

    private static final int REQUEST_CODE = 0; // 请求码
    private PermissionsChecker mPermissionsChecker; // 权限检测器
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.CAMERA
    };
    private String location;
    private DrawerLayout mDrawerLayout;

    //定义FragmentTabHost对象
    private FragmentTabHost fragmentTabHost;

    //定义一个布局
    private LayoutInflater layoutInflater;

    //定义数组来存放Fragment界面
    private Class fragmentArray[] = {HomeFragment.class, ChaperonageFragment.class, MineFragment.class};

    //定义数组来存放按钮图片
    private int mImageViewArray[] = {R.drawable.selector_btn_tab_home, R.drawable.selector_btn_tab_chaperonage,  R.drawable.selector_btn_tab_user};

    //Tab选项卡的文字
    private String mTabNameArray[] = {"首页", "陪护师", "我的"};

    public FragmentManager fragmentManager;

    public BaseFragment currentFragment;

    public static boolean isForeground = false;

    private long exitTime = 0;


    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
               //可在其中解析amapLocation获取相应内容。
                    aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    aMapLocation.getLatitude();//获取纬度
                    Log.e("mainactivity", "纬度:"+aMapLocation.getLatitude());
                    PreferenceUtil.putString(getApplication(),"Latitude",Double.toString(aMapLocation.getLatitude()));

                    aMapLocation.getLongitude();//获取经度
                    Log.e("mainactivity", "经度:"+aMapLocation.getLongitude());
                    PreferenceUtil.putString(getApplication(),"Longitude",Double.toString(aMapLocation.getLongitude()));

                    aMapLocation.getAccuracy();//获取精度信息
                    aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                    Log.e("mainactivity", "地址:"+aMapLocation.getAddress());
                    aMapLocation.getCountry();//国家信息
                    Log.e("mainactivity", "国家:"+aMapLocation.getCountry());
                    aMapLocation.getProvince();//省信息
                    Log.e("mainactivity", "省:"+aMapLocation.getProvince());
                    aMapLocation.getCity();//城市信息
                    Log.e("mainactivity", "城市信息:"+aMapLocation.getCity());
                    aMapLocation.getDistrict();//城区信息
                    Log.e("mainactivity", "城区信息:"+aMapLocation.getDistrict());
                    aMapLocation.getStreet();//街道信息
                    Log.e("mainactivity", "街道信息:"+aMapLocation.getStreet());
                    location=aMapLocation.getAddress();
                    PreferenceUtil.putString(getApplication(),"location",location);
                    aMapLocation.getStreetNum();//街道门牌号信息
                    Log.e("mainactivity", "街道门牌号信息:"+aMapLocation.getStreetNum());
                    aMapLocation.getCityCode();//城市编码
                    Log.e("mainactivity", "城市编码:"+aMapLocation.getCityCode());
                    aMapLocation.getAdCode();//地区编码
                    Log.e("mainactivity", "地区编码:"+aMapLocation.getAdCode());
                    aMapLocation.getAoiName();//获取当前定位点的AOI信息
                    Log.e("mainactivity", "定位点的AOI信息:"+aMapLocation.getAoiName());
                    aMapLocation.getBuildingId();//获取当前室内定位的建筑物Id
                    Log.e("mainactivity", "室内定位的建筑物Id:"+aMapLocation.getBuildingId());
                    aMapLocation.getFloor();//获取当前室内定位的楼层
                    Log.e("mainactivity", "当前室内定位的楼层:"+aMapLocation.getFloor());
                   //获取GPS的当前状态
                    //获取定位时间
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(aMapLocation.getTime());
                    df.format(date);
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        mPermissionsChecker = new PermissionsChecker(this);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.dl_left);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        fragmentManager = getSupportFragmentManager();
        initView();
    }

    /**
     * 初始化组件
     */
    private void initView() {
        //实例化布局对象
        layoutInflater = LayoutInflater.from(this);
        initTabView();
        locate();

    }

    /**
     * 定位
     */
    public  void locate(){
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否强制刷新WIFI，默认为true，强制刷新。
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为true，允许模拟位置
        mLocationOption.setMockEnable(false);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private void initTabView() {

        //实例化TabHost对象，得到TabHost
        fragmentTabHost = (FragmentTabHost) findViewById(R.id.tabs);
        fragmentTabHost.setup(this, getSupportFragmentManager(), R.id.flTabContent);
        fragmentTabHost.getTabWidget().setDividerDrawable(android.R.color.white);

        //得到fragment的个数
        int count = fragmentArray.length;

        for (int i = 0; i < count; i++) {
            //为每一个Tab按钮设置图标、文字和内容
            TabHost.TabSpec tabSpec = fragmentTabHost.newTabSpec(mTabNameArray[i]).setIndicator(getTabItemView(i));
            //将Tab按钮添加进Tab选项卡中
            fragmentTabHost.addTab(tabSpec, fragmentArray[i], null);

        }
    }

    /**
     * 给Tab按钮设置图标和文字
     */
    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.item_tab_view, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.ivTabButton);
        imageView.setImageResource(mImageViewArray[index]);
        TextView textView = (TextView) view.findViewById(R.id.tvTabButton);
        textView.setText(mTabNameArray[index]);
        return view;
    }

    private void startPermissionsActivity() {
        PermissionsActivity.startActivityForResult(this, REQUEST_CODE, PERMISSIONS);
    }


    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
        // 缺少权限时, 进入权限配置页面
        if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
            startPermissionsActivity();
        }

    }


    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    /**
     * 退出按键的设计
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
                mDrawerLayout.closeDrawers();//关闭侧滑菜单
            } else if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出梦城陪护", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 拒绝时, 关闭页面, 缺少主要权限, 无法运行
        if (requestCode == REQUEST_CODE && resultCode == PermissionsActivity.PERMISSIONS_DENIED) {
            finish();
        }
    }
}
